package com.ykdl.member.kid.messagebox;

import java.util.HashMap;
import java.util.Map;

import oauth.signpost.http.HttpParameters;
import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.socialize.utils.Log;
import com.ykdl.member.kid.R;
import com.ykdl.member.constant.KidAction;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.adapters.AttentionAdapter;
import com.ykdl.member.kid.adapters.MessageAdapter;
import com.ykdl.member.kid.adapters.MyLetterAdapter;
import com.ykdl.member.kid.beans.AskDoctorBean;
import com.ykdl.member.kid.beans.AskDoctorBeanListBean;
import com.ykdl.member.kid.beans.DoctorTagBean;
import com.ykdl.member.kid.beans.FeedFriendsBean;
import com.ykdl.member.kid.beans.FeedFriendsListBean;
import com.ykdl.member.kid.beans.HomeMessageCount;
import com.ykdl.member.kid.beans.MessageBean;
import com.ykdl.member.kid.beans.MessageListBean;
import com.ykdl.member.kid.beans.SystemMessageBean;
import com.ykdl.member.kid.beans.SystemMessageListBean;
import com.ykdl.member.kid.circle.TopicAndResultActivity;
import com.ykdl.member.kid.doctor.AskDoctorActivity;
import com.ykdl.member.kid.doctor.ProblemDetailsAcivity;
import com.ykdl.member.kid.gears.BaseScreen;
import com.ykdl.member.kid.image.ImageLoader;
import com.ykdl.member.kid.prefs.MyPrefs;
import com.ykdl.member.kid.util.RequestAsAccessTokenUtil;
import com.ykdl.member.kid.widget.RefreshListView;
import com.ykdl.member.kid.widget.RefreshListView.OnRefreshListener;
import com.ykdl.member.views.IaskMenuBarView;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

public class MyMessageAcivity extends BaseScreen implements OnClickListener{
	private  RefreshListView main_listview ;
	private AttentionAdapter attentionadapter;
	private MyLetterAdapter letteradapter ;
	private MessageAdapter messageadapter;
	private Button dongtai_bt ,xiaoxi_bt ,sixi_bt;
	private final int ATTENTION_TYPE=0;  
	private final int LETTER_TYPE=1;  
    private final int MESSAGE_TYPE=2;
    private int STATES_TYPE ;
    private View header = null;
    private LinearLayout root ;
    private String TAG = "MyMessageAcivity";
    private TextView fans_num ,praises_num;
    private Button go_fans ,go_praises,back_left;
    public static String MESSAGE_TYPE_ID = "message_type_id";
//    private IaskMenuBarView iask_menu_bar ;
    private HomeMessageCount messageCountBean;
    private int start_id = 0;
	private int cursor = 0;
	private int count = 50;
	private boolean isread = true ;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mymessageacivity_xml);
		
		inint();
	}
	public void inint() {
		attentionadapter = new AttentionAdapter(this,TAG);
		letteradapter = new MyLetterAdapter(this,TAG);
		messageadapter = new MessageAdapter(this,isread);
		main_listview = (RefreshListView)findViewById(R.id.main_listview);
		dongtai_bt = (Button)findViewById(R.id.dongtai_bt);
		xiaoxi_bt = (Button)findViewById(R.id.xiaoxi_bt);
		sixi_bt = (Button)findViewById(R.id.sixi_bt);
		back_left=(Button)findViewById(R.id.back_left);
		back_left.setOnClickListener(this);
//		iask_menu_bar = (IaskMenuBarView)findViewById(R.id.iask_menu_bar);
//		if(MyPrefs.getMessageCount(this)!=null||MyPrefs.getChatLetterCount(this)!=null){
//			if (MyPrefs.getChatLetterCount(this)!=null) {
//				sixi_bt.setBackgroundResource(R.drawable.message_xiaoxin_bg_hasnew);
//			}
//			if (MyPrefs.getMessageCount(this)!=null) {
//				xiaoxi_bt.setBackgroundResource(R.drawable.message_sixin_bg_hasnews);
//			}
//			iask_menu_bar.setMessageBar(false);
//		}else {
//			iask_menu_bar.setSelectedID(R.id.bar_personnews);
//		}
//		iask_menu_bar.setBaseScreen(this);
		findViewById(R.id.dongtai_bt).setSelected(true);
		findViewById(R.id.dongtai_bt).setOnClickListener(this);
		findViewById(R.id.xiaoxi_bt).setOnClickListener(this);
		findViewById(R.id.sixi_bt).setOnClickListener(this);
		STATES_TYPE = ATTENTION_TYPE ;
		header = LayoutInflater.from(mContext).inflate(
				R.layout.xiaoxinactivity_head_xml, null);
		root = (LinearLayout)header.findViewById(R.id.root);
		fans_num = (TextView)header.findViewById(R.id.fans_num);
		praises_num = (TextView)header.findViewById(R.id.praises_num);
		go_fans  = (Button)header.findViewById(R.id.go_fans);
		go_praises  = (Button)header.findViewById(R.id.go_praises);
		header.findViewById(R.id.fans_ll).setOnClickListener(this);
		header.findViewById(R.id.praises_ll).setOnClickListener(this);
		main_listview.addHeaderView(header);
		root.setVisibility(View.GONE);
		main_listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if (STATES_TYPE==LETTER_TYPE) {
					MessageBean bean= (MessageBean)letteradapter.getItem(arg2-1);
					Intent intent = new Intent(MyMessageAcivity.this,ChatLetterActivity.class);
					intent.putExtra(KidAction.ACTOR_DIALOGUE_ID, bean.getActor_dialogue_id()+"");
					intent.putExtra(KidAction.DIALOGUE_ID, bean.getDialogue_id()+"");
					MyMessageAcivity.this.startActivityForResult(intent, 0);
				}else if (STATES_TYPE==ATTENTION_TYPE) {
					FeedFriendsBean bean= (FeedFriendsBean)attentionadapter.getItem(arg2-1);
					if (bean.getVerb()==5) {
						//去话题终端页
						Intent intent = new Intent(mContext, TopicAndResultActivity.class);
						intent.putExtra(TopicAndResultActivity.STR_TOPIC_ID, bean.getExtra_context().getTopic().getTopic_id());
						intent.putExtra(TopicAndResultActivity.STR_GROUP_ID, bean.getExtra_context().getTopic().getSource_id());
						MyMessageAcivity.this.startActivityForResult(intent, 0);
					}
				}else if (STATES_TYPE==MESSAGE_TYPE) {
					SystemMessageBean bean= (SystemMessageBean)messageadapter.getItem(arg2-1);
					Intent intent = null ;
					deltnewsList(bean.getGroup());
					if(bean.getVerb()==3){
						intent = new Intent(MyMessageAcivity.this,OfficialMessageActivity.class);
						intent.putExtra(MESSAGE_TYPE_ID, "1");
						MyMessageAcivity.this.startActivityForResult(intent, 0);
						//官方消息
					}else if(bean.getVerb()==4 ){
						// 活动消息
						intent = new Intent(MyMessageAcivity.this,OfficialMessageActivity.class);
						intent.putExtra(MESSAGE_TYPE_ID, "2");
						MyMessageAcivity.this.startActivityForResult(intent, 0);
					}
					else if (bean.getVerb()==5) {
						//去话题终端页
						 intent = new Intent(mContext, TopicAndResultActivity.class);
						intent.putExtra(TopicAndResultActivity.STR_TOPIC_ID, bean.getExtra_context().getTopic_id()+"");
						intent.putExtra(TopicAndResultActivity.STR_GROUP_ID, bean.getExtra_context().getTopic().getSource_id()+"");
						MyMessageAcivity.this.startActivityForResult(intent, 0);
					}else if (bean.getVerb()==6) {
						//二级回复页
						intent = new Intent(mContext, MyReanswerListActivity.class);
						intent.putExtra("parent_post_actor_id", bean.getExtra_context().getPost().getPost_actor_id()+"");
						MyMessageAcivity.this.startActivityForResult(intent, 0);
					}else if (bean.getVerb()==7) {
						//去医生话题
						 intent = new Intent(MyMessageAcivity.this,ProblemDetailsAcivity.class);
						intent.putExtra(KidAction.DOCTOR_TOPICI_DD, bean.getExtra_context().getTopic_id()+"");
						MyMessageAcivity.this.startActivityForResult(intent, 0);
					}
				}
			}
		});
		main_listview.setonRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				cursor = 0;
				if (STATES_TYPE == LETTER_TYPE) {
					getChatLetter();
				} else if (STATES_TYPE == ATTENTION_TYPE) {
					getFeedFriends();

				} else if (STATES_TYPE == MESSAGE_TYPE) {
					getSystemMessage();
				}
			}
			});
		main_listview.setMoreClick(new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (STATES_TYPE == LETTER_TYPE) {
					getChatLetter();
				} else if (STATES_TYPE == ATTENTION_TYPE) {
					getFeedFriends();

				} else if (STATES_TYPE == MESSAGE_TYPE) {
					getSystemMessage();
				}
			}});
		getFeedFriends();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		Log.e("ssss","requestCode:"+requestCode+"--resultCode:"+resultCode);
		if (resultCode==RESULT_OK) {
			messageadapter.setisread(!isread);
			messageadapter.notifyDataSetChanged();
			fans_num.setVisibility(View.GONE);
			praises_num.setVisibility(View.GONE);
			
		}
//		super.onActivityResult(requestCode, resultCode, data);
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.dongtai_bt:
			STATES_TYPE = ATTENTION_TYPE ;
			root.setVisibility(View.GONE);
			main_listview.setAdapter(attentionadapter);
			setSelectedID(R.id.dongtai_bt);
			break;
		case R.id.xiaoxi_bt:
			STATES_TYPE = MESSAGE_TYPE ;
			root.setVisibility(View.VISIBLE);
			setSelectedID(R.id.xiaoxi_bt);
			getSystemMessage();
			break;
		case R.id.sixi_bt:
			root.setVisibility(View.GONE);
			STATES_TYPE = LETTER_TYPE ;
			getChatLetter();
			setSelectedID(R.id.sixi_bt);
			break;
        case R.id.fans_ll:
        	if(!isConnect(this)){
        		Toast.makeText(mContext, "没有网络", 1).show();
        		return;
        	}
        	Intent intent = new Intent(MyMessageAcivity.this,FansActivity.class);
			intent.putExtra("isnewfans",true);
			MyMessageAcivity.this.startActivityForResult(intent, 0);
        	break;
        case R.id.praises_ll:
        	if(!isConnect(this)){
        		Toast.makeText(mContext, "没有网络", 1).show();
        		return;
        	}
        	Intent intent1 = new Intent(MyMessageAcivity.this,PraisesMeListActivity.class);
			intent1.putExtra("isnewfans",true);
			MyMessageAcivity.this.startActivityForResult(intent1, 0);
        	break;
        case R.id.back_left:
        	MyMessageAcivity.this.finish();
		default:
			break;
		}
	}
	public  void setSelectedID(int id) {
		xiaoxi_bt.setBackgroundResource(R.drawable.message_bar_xiaoxi_bg);
		sixi_bt.setBackgroundResource(R.drawable.message_bar_sixi_bg);
		dongtai_bt.setSelected(false);
		xiaoxi_bt.setSelected(false);
		sixi_bt.setSelected(false);
		if (MyPrefs.getChatLetterCount(this)!=null) {
			sixi_bt.setBackgroundResource(R.drawable.message_xiaoxin_bg_hasnew);
		}
		if (MyPrefs.getMessageCount(this)!=null) {
			xiaoxi_bt.setBackgroundResource(R.drawable.message_sixin_bg_hasnews);
		}
		if (MyPrefs.getMessageCount(this)==null&&MyPrefs.getChatLetterCount(this)==null) {
//			iask_menu_bar.setMessageNoBar();
		}
			if (id == R.id.dongtai_bt) {
				dongtai_bt.setSelected(true);
			} else if (id == R.id.xiaoxi_bt) {
				xiaoxi_bt.setSelected(true);
				if (MyPrefs.getMessageCount(this)!=null) {
					xiaoxi_bt.setBackgroundResource(R.drawable.message_xiaoxin_bg_hasnew_now);
					
				}
			}else if (id == R.id.sixi_bt) {
				sixi_bt.setSelected(true);
				if (MyPrefs.getChatLetterCount(this)!=null) {
					sixi_bt.setBackgroundResource(R.drawable.message_xiaoxin_bg_hasnew_now);
				}
			}
		
		
	}
	public void deltnewsList(String group){
		if(!isConnect(this)){
    		Toast.makeText(mContext, "没有网络", 1).show();
    		return;
    	}
		String pageurl=KidConfig.DELT_SYSTEMMESSAGE_LIST;
		HttpParameters bodyParams = new HttpParameters();
		bodyParams.put("group", group);
		HttpBaseRequest request = Wxxr.getInstance().postBaseRequest(pageurl, bodyParams,"");
		TaskManager.startHttpRequest(request, null, null);
	}
	public void getSystemMessage() {
		if(!isConnect(this)){
    		Toast.makeText(mContext, "没有网络", 1).show();
    		return;
    	}
		showProgress("正在加载中,请稍等...");
		String  pageurl =KidConfig.SYSTEMMESSAGE_LIST;
		Map<String,String> map = new HashMap<String, String>();
		map.put("start_id", "0");
		map.put("cursor", "0");
		map.put("count", "50");
		HttpBaseRequest request  =  Wxxr.getInstance().getRequest(pageurl, map,"");
		 TaskManager.startHttpRequest(request, new getSystemMessageTag(),  SystemMessageListBean.class);
	}
	
	class getSystemMessageTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			finishProgress();
			if (t instanceof SystemMessageListBean) {
				SystemMessageListBean bean =(SystemMessageListBean)t;
				Toast.makeText(mContext, "加载成功", 1).show();
				messageadapter.setlist(bean.getMessageList());
				main_listview.setAdapter(messageadapter);
				messageadapter.notifyDataSetChanged();
				hidErrorTip( );
				if (bean.getNew_follower_count()>0) {
					fans_num.setText(bean.getNew_follower_count()+"");
					go_fans.setVisibility(View.GONE);
					fans_num.setVisibility(View.VISIBLE);
				}else {
					go_fans.setVisibility(View.VISIBLE);
					fans_num.setVisibility(View.GONE);
				}
				if (bean.getNew_likes_count()>0) {
					praises_num.setVisibility(View.VISIBLE);
					go_praises.setVisibility(View.GONE);
					praises_num.setText(bean.getNew_likes_count()+"");
				}else {
					praises_num.setVisibility(View.GONE);
					go_praises.setVisibility(View.VISIBLE);
				}
//				if(bean.getNext_cursor()==bean.getTotal_number()){
//					main_listview.setMoreButtoIsGon(true);
//				}
				main_listview.setMoreButtoIsGon(true);
				main_listview.onRefreshComplete();
				main_listview.setFecthMoreOk();
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "加载失败", 1).show();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			
		}
		
	}
	public void getFeedFriends() {
		if(!isConnect(this)){
    		Toast.makeText(mContext, "没有网络", 1).show();
    		return;
    	}
		showProgress("正在加载中,请稍等...");
		String  pageurl =KidConfig.FRIENDS_FEEDS;
		Map<String,String> map = new HashMap<String, String>();
		map.put("start_id", "0");
		map.put("cursor", "0");
		map.put("count", "50");
		HttpBaseRequest request  =  Wxxr.getInstance().getRequest(pageurl, map,"");
		 TaskManager.startHttpRequest(request, new getFeedFriendsTag(),  FeedFriendsListBean.class);
	}
	
	class getFeedFriendsTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "加载成功", 1).show();
			if (t instanceof FeedFriendsListBean) {
				FeedFriendsListBean bean = (FeedFriendsListBean)t;
				if (bean.getList()!=null) {
					attentionadapter.setlist(bean.getList());
					main_listview.setAdapter(attentionadapter);
					attentionadapter.notifyDataSetChanged();
					hidErrorTip( );
				}else {
					showErrorTip("没有数据...", "");
				}
				main_listview.setMoreButtoIsGon(true);
				main_listview.onRefreshComplete();
				main_listview.setFecthMoreOk();
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "加载失败", 1).show();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			
		}
		
	}
	public void getChatLetter() {
		if(!isConnect(this)){
    		Toast.makeText(mContext, "没有网络", 1).show();
    		return;
    	}
		showProgress("正在加载中,请稍等...");
		String  pageurl =KidConfig.PM_INBOX_LIST;
		Map<String,String> map = new HashMap<String, String>();
		map.put("start_id", "0");
		map.put("cursor", "0");
		map.put("count", "50");
		HttpBaseRequest request  =  Wxxr.getInstance().getRequest(pageurl, map,"");
		 TaskManager.startHttpRequest(request, new getChatLetterTag(),  MessageListBean.class);
	}
	
	class getChatLetterTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "加载成功", 1).show();
			if (t instanceof MessageListBean) {
				MessageListBean bean = (MessageListBean)t;
				letteradapter.setlist(bean.getList());
				main_listview.setAdapter(letteradapter);
				main_listview.invalidate();
				letteradapter.notifyDataSetChanged();
				hidErrorTip( );
				main_listview.setMoreButtoIsGon(true);
				main_listview.onRefreshComplete();
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "加载失败", 1).show();
			main_listview.onRefreshComplete();
			main_listview.setFecthMoreOk();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			
		}
		
	}
	protected void onResume() {
		// TODO Auto-generated method stub
		ImageLoader.getInstance().setCurrentActivity(TAG);
		initMessageCount();
//		messageadapter.setisread(!isread);
		messageadapter.notifyDataSetChanged();
		main_listview.setAdapter(messageadapter);
		fans_num.setVisibility(View.GONE);
		praises_num.setVisibility(View.GONE);
		if (STATES_TYPE == LETTER_TYPE) {
			getChatLetter();
		} else if (STATES_TYPE == ATTENTION_TYPE) {
			getFeedFriends();
		} else{
		}
		super.onResume();
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		ImageLoader.getInstance().pause(TAG);
		super.onPause();
	}
	/**
	 * 获取信息数量汇总
	 */
	private void initMessageCount() {
		String url = KidConfig.BASE_TEST_SERVER + "pages/inbox";
		HttpBaseRequest request = Wxxr.getInstance().getRequest(url, null
				);
		TaskManager.startHttpRequest(request, new getMessageCountTag(),
				HomeMessageCount.class);
	}
	class getMessageCountTag implements ITag{
		@Override
		public void refreshUI(Object t, DataState ds) {
			if(null != t && t instanceof HomeMessageCount){
				messageCountBean = (HomeMessageCount)t;
					settingMessageCount();
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			return true;
		}

		@Override
		public void refreshCancel() {
		}
		
	}
	/**
	 * 设置信息数量汇总
	 */
	public void settingMessageCount() {
		if (messageCountBean.getNew_messages_count() > 0
				|| messageCountBean.getNotification_count() > 0) {
			if (messageCountBean.getNew_messages_count() > 0){
				MyPrefs.setChatLetterCount(this, "1");
			}else {
				MyPrefs.setChatLetterCount(this, null);
			}
				
			if (messageCountBean.getNotification_count() > 0) {
				MyPrefs.setMessageCount(this, "1");
			}else {
				MyPrefs.setMessageCount(this, null);
			}
		}else {
			MyPrefs.setMessageCount(this, null);
			MyPrefs.setChatLetterCount(this, null);
		}

			if (STATES_TYPE == LETTER_TYPE) {
				if (MyPrefs.getChatLetterCount(this)!=null) {
					sixi_bt.setBackgroundResource(R.drawable.message_xiaoxin_bg_hasnew_now);
				}else{
					sixi_bt.setBackgroundResource(R.drawable.message_sixin_bg);
				}
				if (MyPrefs.getMessageCount(this)!=null) {
					xiaoxi_bt.setBackgroundResource(R.drawable.message_sixin_bg_hasnews);
				}else{
					xiaoxi_bt.setBackgroundResource(R.drawable.message_xiaoxin_bg);
				}
			} else if (STATES_TYPE == ATTENTION_TYPE) {
				if (MyPrefs.getChatLetterCount(this)!=null) {
					sixi_bt.setBackgroundResource(R.drawable.message_sixin_bg_hasnews);
				}else{
					sixi_bt.setBackgroundResource(R.drawable.message_sixin_bg);
				}
				if (MyPrefs.getMessageCount(this)!=null) {
					xiaoxi_bt.setBackgroundResource(R.drawable.message_sixin_bg_hasnews);
				}else{
					xiaoxi_bt.setBackgroundResource(R.drawable.message_xiaoxin_bg);
				}
			} else if (STATES_TYPE == MESSAGE_TYPE) {
				if (MyPrefs.getChatLetterCount(this)!=null) {
					sixi_bt.setBackgroundResource(R.drawable.message_sixin_bg_hasnews);
				}else{
					sixi_bt.setBackgroundResource(R.drawable.message_sixin_bg);
				}
				if (MyPrefs.getMessageCount(this)!=null) {
					xiaoxi_bt.setBackgroundResource(R.drawable.message_xiaoxin_bg_hasnew_now);
				}else{
					xiaoxi_bt.setBackgroundResource(R.drawable.message_xiaoxin_bg_now);
				}
			}
			
	}

}
